package com.nas.crocus.util;

import java.lang.reflect.Method;

import javax.sql.DataSource;

import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;

public class InjectDataTestExecutionListener extends DependencyInjectionTestExecutionListener {

    
    private static SimpleJdbcTemplate jdbcTemplate;
    private static DataSource datasource;

    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception {
        super.beforeTestClass(testContext);

        Method MyMethdo = testContext.getTestMethod();
        SqlFileLocation dsLocation = MyMethdo.getAnnotation(SqlFileLocation.class);
        if (dsLocation != null) {
            executeSqlScript(testContext, dsLocation.value());
        }
    }

    private void executeSqlScript(TestContext testContext, String sqlResourcePath) {
        ClassPathResource resource = new ClassPathResource(sqlResourcePath);
        DataSource daSource = getDatasource(testContext);
        SimpleJdbcTestUtils.executeSqlScript(getJdbCTemplate(daSource), resource, false);
    }

    private DataSource getDatasource(TestContext testContext) {
        if (datasource == null) {
            datasource = testContext.getApplicationContext().getBean(DataSource.class);
        }
        return datasource;
    }

    private SimpleJdbcTemplate getJdbCTemplate(DataSource datasource) {
        if (jdbcTemplate == null) {
            jdbcTemplate = new SimpleJdbcTemplate(datasource);
        }
        return jdbcTemplate;
    }

}
